import React, {useEffect} from 'react';
import {Layout, Tabs} from "antd";
import {Outlet, useLocation, useNavigate} from "react-router-dom";
import {addItems, delItemsByIndex, useSelectorCommon} from "@/store/slices/common";
import {useAppDispatch, useAppTitleInfo} from "@/hooks";
import type {TTabs} from "@/store/slices/common";

function IndexContent() {
    const {items} = useSelectorCommon();
    const {pathname: key} = useLocation();
    const dispatch = useAppDispatch();
    const info = useAppTitleInfo();
    const navigate = useNavigate();
    useEffect(() => {
        dispatch(addItems({
            key,
            label: info.subTitle as string,
            closable: true
        }))
    }, [key]);
    return (
        <Layout.Content style={{margin: '5px'}}>
            <div className="site-layout-background" style={{padding: 5, height: "100%"}}>
                <Tabs
                    hideAdd={true}
                    type="editable-card"
                    onChange={activekey => navigate(activekey)}
                    activeKey={key}
                    onEdit={activeKey=>{
                        // 根据activeKey找到items数组中对应下标
                        const index = items.findIndex((items:TTabs)=>items.key === activeKey);
                        // 根据index删除items中的数据
                        dispatch(delItemsByIndex(index));
                        // 判断当前路由（key)地址，与点击关闭的地址（activeKey）是否相等。
                        // 如果相等，跳转
                        if(key === activeKey){
                            navigate(items[index-1].key);
                        }
                    }}
                    items={items}
                />
                <Outlet></Outlet>
            </div>
        </Layout.Content>
    );
}

export default IndexContent;